﻿// --------------------------------------------------------------------------------------------------------------------
// <copyright file="CollectionExtensions.cs" company="">
//   
// </copyright>
// <summary>
//   The collection extensions.
// </summary>
// --------------------------------------------------------------------------------------------------------------------
namespace Skymate.Extensions
{
    using System.Collections.Generic;

    /// <summary>
    ///     集合扩展.
    /// </summary>
    public static class CollectionExtensions
    {
        /// <summary>
        /// The add range.
        /// </summary>
        /// <param name="initial">
        /// The initial.
        /// </param>
        /// <param name="other">
        /// The other.
        /// </param>
        /// <typeparam name="T">
        /// </typeparam>
        public static void AddRange<T>(this ICollection<T> initial, IEnumerable<T> other)
        {
            if (other == null)
            {
                return;
            }

            var list = initial as List<T>;

            if (list != null)
            {
                list.AddRange(other);
                return;
            }

            other.Each(initial.Add);
        }

        /// <summary>
        /// 非空扩展.
        /// </summary>
        /// <param name="source">
        /// The source.
        /// </param>
        /// <typeparam name="T">
        /// </typeparam>
        /// <returns>
        /// The <see cref="bool"/>.
        /// </returns>
        public static bool IsNullOrEmpty<T>(this ICollection<T> source)
        {
            return source == null || source.Count == 0;
        }

        /// <summary>
        /// 集合内容全部一致.
        /// </summary>
        /// <param name="a">
        /// The a.
        /// </param>
        /// <param name="b">
        /// The b.
        /// </param>
        /// <typeparam name="T">
        /// </typeparam>
        /// <returns>
        /// The <see cref="bool"/>.
        /// </returns>
        public static bool EqualsAll<T>(this IList<T> a, IList<T> b)
        {
            if (a == null || b == null)
            {
                return a == null && b == null;
            }

            if (a.Count != b.Count)
            {
                return false;
            }

            var comparer = EqualityComparer<T>.Default;

            for (var i = 0; i < a.Count; i++)
            {
                if (!comparer.Equals(a[i], b[i]))
                {
                    return false;
                }
            }

            return true;
        }
    }
}